#include <iostream>
#include "boost/thread/mutex.hpp"
#include "boost/thread/thread.hpp"
using namespace std;
typedef boost::shared_lock<boost::shared_mutex> readLock;
typedef boost::unique_lock<boost::shared_mutex> writeLock;

boost::shared_mutex rwmutex;

std::vector<int> shared_vec = {1, 2};

int pause1 = 0;

void wait(int milliseconds)
{
	boost::this_thread::sleep(boost::posix_time::milliseconds(milliseconds));
}

void readThread1()
{
	while (true)
	{
		wait(100);
		if (pause1)
		{
			continue;
		}

		readLock  rdlock(rwmutex);
		printf("rthread 1: vec[1]: %d\n", shared_vec[1]);
	}
}

void readThread2()
{
	while (true)
	{
		wait(100);
		if (pause1)
		{
			continue;
		}

		readLock  rdlock(rwmutex);
		printf("rthread 2: vec[2]: %d\n", shared_vec[2]);
	}
}

void writeThread()
{
	int count = 1;
	while (true)
	{
		count++;

		wait(500);
		if (pause1)
		{
			continue;
		}
                  
        writeLock wdlock(rwmutex);
		shared_vec[1] = count;
		shared_vec[2] = count + 1;

		printf("wthread 2: vec[1] and vec[2]: %d %d\n", shared_vec[1], shared_vec[2]);

		if (count >= 100)
		{
			count = 0;
		}
	}
}


int main(void)
{
	boost::thread t1(readThread1);
	wait(20);
	boost::thread t2(readThread2);
	wait(20);
	boost::thread t3(writeThread);

	while (true)
	{
		char c = getchar();
		if (c == 's')
		{
			pause1 = 1;
		}
		else if (c == 'r')
		{
			pause1 = 0;
		}
		else if (c == 'q')
		{
			break;
		}

		wait(500);

	}
	return 0;
}